package swordoffer.offer05;

public class IfInputTypeIsStringBuilder {
    public String replaceSpace(StringBuffer str) {
        int length = str.length();
        int spaceNum = 0;
        for (int i = 0; i < length; i++) {
            if (str.charAt(i) == ' ') {
                spaceNum++;
            }
        }
        int oldIndex = length - 1;
        str.setLength(length + 2 * spaceNum);
        int newIndex = str.length() - 1;
        while (oldIndex != newIndex) {
            if (str.charAt(oldIndex) == ' ') {
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
            } else {
                str.setCharAt(newIndex--, str.charAt(oldIndex));
            }
            oldIndex--;
        }
        return str.toString();
    }
}
